﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CarbonExchange.WebControls;
using CarbonExchange.Bll;

public partial class UserControls_CarbonFootprintQuestion_Transport_Flights : CarbonExchange.WebControls.AuditQuestionSigleItemBase
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rptFlights.ItemDataBinding += new EventHandler<CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs>(rptFlights_ItemDataBinding);
    }

    void rptFlights_ItemDataBinding(object sender, CarbonExchange.WebControls.AmeeRepeater.ItemEventArgs e)
    {
        AmeeDrillDown ameeFrom = e.Item.FindControl("ameeFrom") as AmeeDrillDown;
        AmeeDrillDown ameeTo = e.Item.FindControl("ameeTo") as AmeeDrillDown;
        DropDownList ddlReturn = e.Item.FindControl("ddlReturn") as DropDownList;
        DropDownList ddlPeople = e.Item.FindControl("ddlPeople") as DropDownList;
        DropDownList ddlNoOfTimes = e.Item.FindControl("ddlNoOfTimes") as DropDownList;
        DropDownList ddlOffset = e.Item.FindControl("ddlOffset") as DropDownList;

        if (ameeFrom != null && ameeTo != null && ddlReturn != null && ddlPeople != null && ddlNoOfTimes != null && ddlOffset != null)
        //if (ameeFrom != null && ameeTo != null && ddlReturn != null && txtPeople != null && ddlOffset != null)
        {
            ameeFrom.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeFrom_{0}", e.Item.ItemIndex)));
            ameeTo.AddOptions(Answer.GetSetting<AmeeDrillDown.Option[]>(string.Format("ameeTo_{0}", e.Item.ItemIndex)));
            ddlReturn.Text = Answer.GetSetting<string>(string.Format("ddlReturn_{0}", e.Item.ItemIndex));
            ddlPeople.Text = Answer.GetSetting<string>(string.Format("ddlPeople_{0}", e.Item.ItemIndex));
            ddlNoOfTimes.Text = Answer.GetSetting<string>(string.Format("ddlNoOfTimes_{0}", e.Item.ItemIndex));
            ddlOffset.Text = Answer.GetSetting<string>(string.Format("ddlOffset_{0}", e.Item.ItemIndex));
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public override void  DataBind()
    {
        rptFlights.SetNumberOfItems(Answer.GetSetting<int>("rptFlights"));
        base.DataBind();
    }

    protected override bool SaveQuestion()
    {
        var completed = true;
        AmeeProfileItemFactory profileItemfactory = new AmeeProfileItemFactory();
        AmeeDataCatagoryFactory dataCategoryfactory = new AmeeDataCatagoryFactory();

        List<AnswerItem> itemsToKeep = new List<AnswerItem>();
        Answer.SetSetting<int>("rptFlights", rptFlights.Items.Count());
        foreach (var item in rptFlights.Items)
        {
            AmeeDrillDown ameeFrom = item.FindControl("ameeFrom") as AmeeDrillDown;
            AmeeDrillDown ameeTo = item.FindControl("ameeTo") as AmeeDrillDown;
            DropDownList ddlReturn = item.FindControl("ddlReturn") as DropDownList;
            DropDownList ddlPeople = item.FindControl("ddlPeople") as DropDownList;
            DropDownList ddlNoOfTimes = item.FindControl("ddlNoOfTimes") as DropDownList;
            DropDownList ddlOffset = item.FindControl("ddlOffset") as DropDownList;
            var name = string.Format("Flight_{0}", item.ItemIndex);
            //if (ameeFrom != null && ameeTo != null && ddlReturn != null && txtPeople != null && ddlOffset != null)
            if (ameeFrom != null && ameeTo != null && ddlReturn != null && ddlPeople != null && ddlOffset != null)
            {
                Answer.SetSetting<AmeeDrillDown.Option[]>(string.Format("ameeFrom_{0}", item.ItemIndex), ameeFrom.SelectedOptions);
                Answer.SetSetting<AmeeDrillDown.Option[]>(string.Format("ameeTo_{0}", item.ItemIndex), ameeTo.SelectedOptions);
                Answer.SetSetting<string>(string.Format("ddlReturn_{0}", item.ItemIndex), ddlReturn.Text);
                Answer.SetSetting<string>(string.Format("ddlPeople_{0}", item.ItemIndex), ddlPeople.Text);
                Answer.SetSetting<string>(string.Format("ddlNoOfTimes_{0}", item.ItemIndex), ddlNoOfTimes.Text);
                Answer.SetSetting<string>(string.Format("ddlOffset_{0}", item.ItemIndex), ddlOffset.Text);

                string choice = string.Format("type=auto&size={0}", ddlReturn.SelectedValue == "1" ? "return" : "one way");

                var tmpProfileItem = EnsureProfileItem(name, profileItemfactory, dataCategoryfactory, "transport/plane/generic", choice);

                bool save = string.IsNullOrEmpty(tmpProfileItem.Id);

                string fromCode = null;
                if (ameeFrom.CurrentCategory.DataItemSelected)
                {
                    var fromName = ameeFrom.CurrentCategory.Selected.Where(x => x.Name == "airportName").Single().Value.ToString();
                    fromCode = GetCode(fromName);
                }
                else
                {
                    completed = false;
                }

                string toCode = null;
                if (ameeTo.CurrentCategory.DataItemSelected)
                {
                    var toName = ameeTo.CurrentCategory.Selected.Where(x => x.Name == "airportName").Single().Value.ToString();
                    toCode = GetCode(toName);
                }
                else
                {
                    completed = false;
                }

                if (tmpProfileItem.GetValue<string>("IATACode1") != fromCode)
                {
                    tmpProfileItem.SetValue<string>("IATACode1", fromCode);
                    save = true;
                }

                if (tmpProfileItem.GetValue<string>("IATACode2") != toCode)
                {
                    tmpProfileItem.SetValue<string>("IATACode2", toCode);
                    save = true;
                }

                int noOfTimes = 1;
                try
                {
                    noOfTimes = int.Parse(ddlNoOfTimes.Text);
                }
                catch{}

                if (tmpProfileItem.GetValue<int>("journeysPerYear") != noOfTimes)
                {
                    tmpProfileItem.SetValue<int>("journeysPerYear", noOfTimes);
                    save = true;
                }

                //it is a decimal in amee even thoiugh obviosly should be an int
                decimal noOfPeople = 1;
                try
                {
                    noOfPeople = int.Parse(ddlPeople.Text);
                }
                catch (FormatException)
                {
                }

                if (tmpProfileItem.GetValue<decimal>("numberOfPassengers") != noOfPeople)
                {
                    tmpProfileItem.SetValue<decimal>("numberOfPassengers", noOfPeople);
                    save = true;
                }

                if (save)
                {
                    profileItemfactory.Save(tmpProfileItem);
                }

                float factor = 1f/12f;
                //if offest set to 0
                if (ddlOffset.SelectedValue == "1")
                {
                    factor = 0;
                }

                itemsToKeep.Add(Answer.SetItem(name, tmpProfileItem, factor));
            }
        }
        var deleteItems = Answer.AnswerItems.Where(x => !itemsToKeep.Contains(x)).ToList();

        if (deleteItems.Count > 0)
        {
            CarbonExchange.Bll.AnswerItemFactory answerItemFactory = new CarbonExchange.Bll.AnswerItemFactory();
            answerItemFactory.Delete(deleteItems);
            foreach (var del in deleteItems)
            {
                if (Answer.AnswerItems.Contains(del))
                    Answer.AnswerItems.Remove(del);
            }
        }
        return completed;
    }

    private string GetCode(string toName)
    {
        string tmp = toName.Substring(toName.IndexOf("[") + 1);
        tmp = tmp.Substring(0, tmp.IndexOf("]"));
        return tmp;
    }

}
